#include "interrupts.h"
#include "kbd.h"
#include "descriptors.h"
#include "pic.h"
#include "kernel.h"
#include "stdio.h"

/* table of the body of the interrupt handlers */
interrupt_t interrupt_handlers[MAX_INTERRUPTS];

void handle_interrupt(registers r) {
  interrupt_handlers[r.int_no]();
}

void dummy_handler() {
  return;
}

void register_isr(int no, interrupt_t i) {
  interrupt_handlers[no] = i;
}

// various handlers for processor exceptions
void divide_error() {
  kprintf("Division error\n");
  //while(1);
}

void overflow() {
  kprintf("Overflow error\n");
  //while(1);
}

void double_fault() {
  kprintf("Double Fault!!\n" );
  while(1);
}

void invalid_tss() {
  kprintf("Invalid TSS\n");
}

void stack_exception() {
  kprintf("Stack exception\n");
}

void triple_fault() {
  kprintf("Triple Fault!!!\n");
  while(1);
}

void init_interrupts() {
  int i;
  // setup desciptor table
  init_IDT();

  for(i = 0; i < MAX_INTERRUPTS; ++i) 
    interrupt_handlers[i] = dummy_handler;
  
  // setup exception handlers
  register_isr(DIVIDE_ERROR_NO, divide_error);
  register_isr(OVERFLOW_NO, overflow);
  register_isr(DOUBLE_FAULT_NO, double_fault);
  register_isr(INVALID_TSS_NO, invalid_tss);
  register_isr(STACK_EXCEPTION_NO, stack_exception);
  register_isr(TRIPLE_FAULT_NO, triple_fault);	
}
